package com.dwring.mvcframe.utils;

import java.io.File;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.input.SAXBuilder;

import com.dwring.mvcframe.model.XmlBean;

public class XmlHelper {

	public static Map<String, Object> initXml(String xmlPath) throws Exception {
		SAXBuilder builder = new SAXBuilder();
		Document document = builder.build(new File(xmlPath));
		Element root = document.getRootElement();
		Element actionRoot = root.getChild("action-mapping");
		List<Element> actionMapping = actionRoot.getChildren();
		Map<String, Object> rootMap = new HashMap<String, Object>();
		for (Element e : actionMapping) {
			String name = e.getAttributeValue("name");
			Element actionForm = root.getChild("formbeans");
			List<Element> form = actionForm.getChildren();
			System.out.println("------------------"+name);
			XmlBean action = new XmlBean();
			for (Element ex : form) {
				if (name.equals(ex.getAttributeValue("name"))) {
					String formClass = ex.getAttributeValue("class");
					System.out.println("===========CLass XML======");
					action.setFormClass(formClass);
					break;

				}
			}
			String path = e.getAttributeValue("path");
			action.setPath(path);
			String actionType = e.getAttributeValue("type");
			action.setActionType(actionType);
			List<Element> forward = e.getChildren();
			Map<String, String> actionForward = new HashMap<String, String>();
			for (Element x : forward) {
				String fName = x.getAttributeValue("name");
				String fValue = x.getAttributeValue("value");
				actionForward.put(fName, fValue);
				System.out.println(" forward Name:" + fName + " ||" + fValue);
			}
			action.setActionForward(actionForward);
			rootMap.put(path, action);
		}
		return rootMap;
	}

//	public static void main(String[] args) throws Exception {
//		Map<String, Object> map = new XmlHelper().initXml();
//		Set<String> keySet = map.keySet();
//		for (Iterator<String> iter = keySet.iterator(); iter.hasNext();) {
//			String key = iter.next();
//			System.out.println(key);
//			System.out.println(map.get(key));
//		}
//	}
}
